package org.madgecko.basic.controller;

import org.madgecko.basic.model.Pager;
import org.madgecko.basic.model.Clazz;
import org.madgecko.basic.model.ExtGridReturn;
import org.madgecko.basic.model.ExtReturn;
import org.madgecko.basic.model.User;
import org.madgecko.basic.service.iface.IClazzService;
import org.madgecko.basic.service.iface.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/clazz")
public class ClazzController {

	@Inject
	private IClazzService clazzService;
	@Inject
	private IUserService userService;

	@ResponseBody
	@RequestMapping(value = "/add", produces={"application/json; charset=UTF-8"})
	public Object add(Clazz clazz, HttpSession session){
		clazz.setCreateDate(new Date());
		User user = (User)session.getAttribute("user");
		clazz.setOwner(userService.load(user.getId()));
		clazz.setAuthorName(user.getRealName());
		clazzService.add(clazz);
		return new ExtReturn(true);
	}

	@ResponseBody
	@RequestMapping(value = "/delete/{id}" , produces={"application/json; charset=UTF-8"})
	public Object delete(@PathVariable Integer id){
		clazzService.delete(id);
		return new ExtReturn(true);
	}

	@ResponseBody
	@RequestMapping(value = "/update", produces={"application/json; charset=UTF-8"})
	public Object update(Clazz clazz){
		Clazz dbc = clazzService.load(clazz.getId());
		dbc.setDes(clazz.getDes());
		dbc.setName(clazz.getName());
		dbc.setUpdateDate(new Date());
		clazzService.update(dbc);
		return new ExtReturn(true);
	}

	@ResponseBody
	@RequestMapping(value = "/toggleStatus/{id}", produces={"application/json; charset=UTF-8"})
	public Object toggleStatus(@PathVariable Integer id){
		Clazz dbc = clazzService.load(id);
		if(dbc.getStatus()==0){
			dbc.setStatus(1);
		}else if(dbc.getStatus()==1){
			dbc.setStatus(0);
		}
		clazzService.update(dbc);
		return new ExtReturn(true);
	}

	@ResponseBody
	@RequestMapping(value = "/findClazzByCon", produces={"application/json; charset=UTF-8"})
	public Object findClazzByCon(Integer status, String con){
		Pager<Clazz> pc = clazzService.findClazzByCon(status, con);
		return new ExtGridReturn(pc.getTotal(), pc.getDatas());
	}

	@ResponseBody
	@RequestMapping(value = "/listInSchoolClazz", produces={"application/json; charset=UTF-8"})
	public Object listInSchoolClazz(){
		List<Clazz> lc = clazzService.listInSchoolClazz();
		return new ExtGridReturn((long)lc.size(), lc);
	}

}
